package com.hk.service.business;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.hk.annotation.GetMessage;
import com.hk.enums.OuterErrorEnum;
import com.hk.service.business.message.AbstractMessageBusiness;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: dpb
 * @Description TODO
 * @date: 2023/2/1 11:27
 * @Version 1.0
 */
@Service
@Slf4j
public class MessageBusinessFactory implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    private static Map<String, AbstractMessageBusiness> REQUEST_MAP = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, AbstractMessageBusiness> beansOfType = applicationContext.getBeansOfType(AbstractMessageBusiness.class);
        if (MapUtil.isNotEmpty(beansOfType)) {
            for (Map.Entry<String, AbstractMessageBusiness> entry : beansOfType.entrySet()) {
                AbstractMessageBusiness entity = entry.getValue();
                GetMessage annotation = AnnotationUtil.getAnnotation(entity.getClass(), GetMessage.class);
                if (Objects.nonNull(annotation)) {
                    REQUEST_MAP.put(annotation.msg(), entity);
                }
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    public AbstractMessageBusiness fetchService(String msg) {
        Assert.isTrue(StringUtils.isNotBlank(msg), OuterErrorEnum.FACTORY_PARAM_ISNULL_ERROR.getMsg());
        Assert.isTrue(MapUtil.isNotEmpty(REQUEST_MAP),OuterErrorEnum.FACTORY_MAP_ISNULL_ERROR.getMsg());
        return REQUEST_MAP.get(msg);
    }


}
